<template>
	<view class="tab-content">
		<view class=" uni-common-mt">
			<uni-segmented-control :current="current" :values="tabBars" style-type="button"
				active-color="#18bc9c" @clickItem="onClickItem" />
		</view>

		<view v-show="current === 0">
			<tableHead :poorder="poorder" prestr="SEOUT" 
			:order_type="5" ref="thead"></tableHead>
		</view>

		<view v-show="current === 1">
			<scroll-view scroll-y="true" style="height: 80vh;">
				<view class="form_list">
					<showMaterialList :dataArr="porderItem" :orderType="5" flag='out' 
					:checkKc="true" :showShelves="false" :showShelvesName="true" 
					ref="showMaterialList" :showProgress="true" :progressVal="progressVal">
					</showMaterialList>
				</view>
			</scroll-view>
			<view class="swiper-button">
				<button @click="$refs.thead.toSerial()">选择源单</button>
				<button @click="checkOrder" class="ok_btn">完成</button>
			</view>
		</view>
	</view>
</template>

<script>
	import tableHead from "@/component/table-head.vue"
	import showMaterialList from "@/component/show-material-list.vue"
	import {
		uniSegmentedControl
	} from '@dcloudio/uni-ui'
import { forEach } from "core-js/es7/array"
	export default {
		components: {
			uniSegmentedControl,tableHead,showMaterialList
		},
		data() {
			return {
				current: 1,
				/* 选中标签栏的序列,默认显示第一个 */
				tabBars: ['表头', '表体'],
				
				poorder: {}, //源单对象
				porderItem: [],//动态变化的数组
				porderItemOld:[],//最初的明细，用于判断比较上面变化的数组
				
				planItem:[],//销售单计划表体
				progressVal:0,
				totalNum:0,//应发总数
				InvnumberArr:[],//本次发送物料款式
				qrNoArr:[],
				qrNoInvCbatArr:[],
				operflag:'add',//默认新增
				
				user:uni.getStorageSync('user')
			}
		},
		computed: {},
		watch:{
			porderItem:{
				handler(newVal,oldVal){
					let pushTotalNum = 0
					newVal.forEach((item,key)=>{
						pushTotalNum += parseFloat(item.real_quantity)
					})
					this.progressVal = this.$Func.decimalPattern(pushTotalNum*100/this.totalNum)
				},
				deep: true
			}
		},
		onLoad(options) { 
			this.$Func.setBarTitle('销售出库')
			//初始化
			setTimeout(()=>{
				this.$refs.thead.init() //初始化
			},500)
			
			uni.$off("getMarr")
			uni.$on("getMarr", (value,operflag='add') => {
				
				if (JSON.stringify(this.poorder) == "{}") {
					this.$Api.msg('请选择源单','error');
					return;
				}
				
				//let checkitem = this.porderItem.find(ele=>ele.inv_number == value.number && ele.cBatch == value.cBatch)
				//if(checkitem==undefined){//不存在
					let check = this.planItem.find(ele => ele.inv_number == value.number )
					if(check!=undefined){//存在
						let eleNew = Object.assign({}, check)
						//3 固定库区，成品区
						//this.$Db.getKc(value.number,this.user.stock_id,'',value.cBatch).then(kc_res=>{
						this.$Db.getKc(value.number,this.user.stock_id,3,value.cBatch).then(kc_res=>{
							//console.log(kc_res)
							if(!kc_res.length){
								this.$Api.msg(this.user.stock_name+'-成品区-不存在该批号库存')
								return
							}
							
							//这里特殊指定货架3，成品区，才能这么判断
							let checkitemkc = this.porderItem.find(ele=>ele.inv_number == value.number && ele.cBatch == value.cBatch && ele.shelves_id == 3)
							if(checkitemkc!=undefined){//&&operflag=='add'
								//存在
								if(value.qrNo!=''){
									let qrNoArr = []
									if(checkitemkc.qrNo!=''){
										qrNoArr = checkitemkc.qrNo.split(',')
									}
									
									if(!this.$Func.inArray(value.qrNo,qrNoArr)){
										qrNoArr.push(value.qrNo)
										checkitemkc.qrNo = qrNoArr.join(',')
									}
								}
								this.$Api.msg('已存在该物料批号扫码记录')
								return
							}
							
							let fqty = kc_res[0].fqty //即时库存
							let fauxqty = kc_res[0].store_quantity//常用数量
							//合并同个inv_number的数量
							let mergePlanArr = this.$Func.arraySameKeySum(this.planItem,'inv_number','real_store_quantity')
							let mergeItemArr = this.$Func.arraySameKeySum(this.porderItem,'inv_number','real_store_quantity')
							let checkplan = mergePlanArr.find(ele => ele.inv_number == value.number )//得到发货单该物料总数
							let checkitem = mergeItemArr.find(ele => ele.inv_number == value.number )//已扫码发货单该物料总数
							
							if(checkplan!=undefined){
								if(checkitem!=undefined){
									//有扫码记录
									for(let pi of this.porderItem){
										if(pi.inv_number==checkitem.inv_number&&pi.cBatch==value.cBatch){
											fauxqty-=pi.real_store_quantity
										}
									}
									if(fauxqty<=0){
										this.$Api.msg("该二维码数量已出完")
										return 
									}
									
									let cha = checkplan.real_store_quantity - checkitem.real_store_quantity
									if(cha<=0&&operflag=='add'){
										this.$Api.msg(check.inv_name+"应出数量已足够")
										return 
									}else{
										//剩余大于库存，按库存
										if(cha>fauxqty){
											eleNew.real_store_quantity = fauxqty
											eleNew.real_quantity = fauxqty*Number(kc_res[0].fCoefficient)
										}else{
											eleNew.real_store_quantity = cha
											eleNew.real_quantity = cha*Number(kc_res[0].fCoefficient)
										}
									}
								}else{
									//无扫码记录
									if(checkplan.real_store_quantity<fauxqty){//库存大于计划数
										eleNew.real_quantity = checkplan.real_store_quantity*Number(kc_res[0].fCoefficient)
										eleNew.real_store_quantity = checkplan.real_store_quantity
									}else{//库存小于计划数
										eleNew.real_quantity = fqty//基本数量
										eleNew.real_store_quantity = kc_res[0].store_quantity//常用数量
									}
								}
								
								eleNew.real_quantity = this.$Func.decimalPattern(eleNew.real_quantity)
								eleNew.real_store_quantity = this.$Func.decimalPattern(eleNew.real_store_quantity)
								//20240202
								eleNew.quantity = checkplan.real_store_quantity*Number(kc_res[0].fCoefficient) //应出数量
							}
							
							eleNew.kc_quantity = fqty
							eleNew.cBatch = value.cBatch
							eleNew.shelves_id = kc_res[0].shelves_id
							eleNew.shelves_name = kc_res[0].shelves_name
							eleNew.qrNo = value.qrNo
							
							this.porderItem.push(eleNew)
							
							if(operflag=='add'){
								this.$Api.msg('已添加','info')
							}
						})
					}else{
						this.$Api.msg('订单不存在该物料')
					}
				// }else{
				// 	this.$Api.msg('已存在该物料批号')
				// }
			})
		},
		destroyed() {
			uni.$off('getMarr')
		},
		onShow() {
			//监听选择源单
			uni.$off("getAppmaterial")
			uni.$once("getAppmaterial", (value,operflag) => {
				this.operflag = operflag
				
				this.reset()
				this.poorder = value
				this.$refs.thead.remark = value.remark
				
				uni.showLoading({mask:true});
				this.$Db.selectTableData('outask', 'pcode', value.pcode).then(res => {//appmaterial
					this.porderItem = []//先清空之前
					this.porderItemOld = []//先清空之前old
					this.planItem = []
					this.InvnumberArr = []
					this.progressVal = 0
					this.totalNum = 0
					
					res.forEach((arr) => {
						arr.real_quantity = this.$Func.decimalPattern(arr.quantity - arr.commit_quantity) //实出
						arr.quantity = arr.real_quantity  //应出
						arr.real_store_quantity = Number(arr.real_quantity/arr.fCoefficient)//常用数量
						
						arr.shelves_id = 0 //初始化为0
						arr.shelves_name = ''
						if(arr.seorder_batch_shelves!=''){
							//订单自带批号
							let temp = arr.seorder_batch_shelves.split('_')
							arr.shelves_id = temp[0]
							arr.shelves_name = temp[1]
						}
						
						if(arr.quantity>0){
							this.totalNum += arr.real_quantity //计算销售出库总数 基本
							this.planItem.push(arr)
							this.InvnumberArr.push(arr.inv_number)
							//this.porderItem.push(arr)
							//this.porderItemOld.push(arr)
						}
					});
					
					//编辑
					if(this.operflag=='edit'){
						this.$Db.selectTableData('stockbillentry','FBillNo',this.poorder.FBillNo).then(res=>{
							res.forEach((item,index) => {
								let eleNew = Object.assign({}, item)
								eleNew.number = item.inv_number
								eleNew.real_quantity = item.fqty //本次应出数
								eleNew.real_store_quantity = item.fauxqty //常用数
								eleNew.unit_code = item.inv_unit_code
								eleNew.unit_name = item.inv_unit
								eleNew.qrNo = item.inv_attributes
								
								//加入数组
								uni.$emit('getMarr',eleNew,'edit')
								//更新货架
								//this.$set(this.porderItem,index,eleNew)
							})
							
							this.poorder.cUser_Id = value.factory_code
							this.poorder.cUser_Name = value.factory_name
							//this.$refs.thead.qrNoStr = value.rd_name
							this.$refs.thead.FBillNo = value.FBillNo
							uni.hideLoading();
							this.current = 1
						})
					}else{
						uni.hideLoading();
					}
					
					this.InvnumberArr = this.$Func.uniqueArr(this.InvnumberArr)
				})
			})
		},
		methods: {
			onClickItem(e) {
				if (this.current !== e.currentIndex) {
					this.current = e.currentIndex
				}
			},
			//核实物料
			async checkOrder() {
				if (JSON.stringify(this.poorder) == "{}"||this.porderItem.length == 0) {
					this.$Api.msg('请选择源单','error');
					return;
				}
				
				// if(this.progressVal!=100){
				// 	this.$Api.msg('出库物料未扫全,请核实');
				// 	return;
				// }
				
				let check_total = 0 //总数不能为0
				let overflag = false
				let billentry = []
				let newPorderItem = []
				let newQrNoArr = []
				
				//分解流水码
				// if(this.$refs.thead.qrNoStr!=''&&this.qrNoInvCbatArr.length>0){
				// 	let qrNoArr = this.$refs.thead.qrNoStr.split(',')
					
				// 	this.qrNoInvCbatArr.forEach((item, index) => {
				// 		let tarr = item.split('_')
				// 		if(tarr[2]!=undefined&&tarr[2]!=''&&this.$Func.inArray(tarr[2],qrNoArr)){
				// 			newQrNoArr.push(item)
				// 		}
				// 	})
				// }
				
				let scan_inv_number_arr = []
				this.porderItem.forEach((item,index)=>{
					scan_inv_number_arr.push(item.inv_number)
				})
				scan_inv_number_arr = this.$Func.uniqueArr(scan_inv_number_arr)
				if(scan_inv_number_arr.length!=this.InvnumberArr.length){
					this.$Api.msg('出库物料未扫全,请核实');
					return;
				}
				
				for(let i in this.porderItem){
					let citem = this.porderItem[i]
					let real_quantity = parseFloat(citem.real_quantity)
					let quantity = parseFloat(citem.quantity)
					let kc_quantity = parseFloat(citem.kc_quantity)
					let commit_quantity = parseFloat(citem.commit_quantity)
					
					if(real_quantity == 0 || isNaN(real_quantity)){
						continue
					}
					
					check_total += real_quantity //累加总数 
					
					//实收数量超过应收提示
					// if(real_quantity>quantity){
					// 	this.$Api.msg(citem.inv_name+'实出数量大于应出数');
					// 	return ;
					// }
					
					if(citem.shelves_id == ''||citem.shelves_id == 0) {
						this.$Api.msg(citem.inv_name+'目标库区为空,请重选批号')
						// setTimeout(()=>{
						// 	this.$refs.showMaterialList.toGetShelves(i,0,citem.inv_number,citem.cBatch)
						// },1000)
						return
					}
					
					if(real_quantity>kc_quantity){
						this.$Api.msg(citem.inv_name+'实出数量大于库存数')
						return
					}
					
					let inv_attributes_arr = []
					//拆分流水号
					if(newQrNoArr.length>0){
						newQrNoArr.forEach((item) => {
							let tarr = item.split('_')
							if(tarr[0]==citem.inv_number&&tarr[1]==citem.cBatch){
								inv_attributes_arr.push(tarr[2])
							}
						})
					}
					
					//单据表体添加
					billentry.push({
						'FBillNo':this.$refs.thead.FBillNo,
						'auto_id':citem.auto_id,
						'row_id':citem.row_id,
						'local_row_id':i,
						'inv_number':citem.inv_number,
						'inv_name':citem.inv_name,
						'inv_specification':citem.inv_specification,
						'inv_attributes':citem.qrNo!=undefined?citem.qrNo:'',
						'inv_unit':citem.unit_name,
						'inv_unit_code':citem.unit_code,
						'store_unit':citem.store_unit,
						'store_unit_code':citem.store_unit_code,
						'fqty':real_quantity,
						'fauxqty':citem.real_store_quantity,
						'cBatch':citem.cBatch,
						'shelves_id':citem.shelves_id,
						'shelves_name':citem.shelves_name,
						'shelves_type':citem.shelves_type,
						'b_remark':''
					})
					
					//应出数
					citem.no_quantity = this.$Func.decimalPattern(quantity - commit_quantity)
					newPorderItem.push(citem)
				}
				
				if(!check_total||!billentry.length||isNaN(check_total)){
					this.$Api.msg("出库数量全为0")
					return 
				}
				
				/* if(this.$refs.thead.to_shelves_id==''||isNaN(this.$refs.thead.to_shelves_id)){
					this.$Api.msg("请选择暂存路径")
					this.current = 0
					return 
				} */
				
				let flag = true
				check_total = this.$Func.decimalPattern(check_total)//小数点后x位
				
				//合并同个inv_number的数量
				let mergePlanArr = this.$Func.arraySameKeySum(this.planItem,'inv_number','real_store_quantity')
				//合并同个inv_number的数量
				let mergePdaArr = this.$Func.arraySameKeySum(newPorderItem,'inv_number','real_store_quantity')
				
				for(let mergePda of mergePdaArr){
					let check = mergePlanArr.find(ele => ele.inv_number == mergePda.inv_number )
					let inventory = newPorderItem.find(ele => ele.inv_number == mergePda.inv_number )
					if(check!=undefined){
						if(mergePda.real_store_quantity>check.real_store_quantity){
							this.$Api.msg(inventory.inv_name+'-实出数量大于应出数,请核实')
							return 
						}
					}
				}

				//表头
				let bill = {//准备表头数据
					//'auto_id':this.poorder.auto_id,
					'source_code':this.poorder.pcode,
					'order_type':5,//销售出库单
					'FBillNo':this.$refs.thead.FBillNo,
					'FDate':this.$refs.thead.FDateVal,
					'a_remark':this.$refs.thead.remark,
					'stock_id':this.$refs.thead.stock_id,
					//'to_shelves_id':this.$refs.thead.to_shelves_id,
					//'to_shelves_name':this.$refs.thead.to_shelves_name,
					'status':1,
					'syn_status':0,
					'total_qty':check_total,
					'factory_code':this.poorder.cUser_Id,
					'factory_name':this.poorder.cUser_Name,
					'userid':this.user.userid,
					'rd_name':this.$refs.thead.qrNoStr,
					'create_date':this.$Func.getDateTime('today','Y-m-d')
				}
				
				//判断是否存在重复记录 -- 同个货架，同个物料，拣货多次
				if(flag){
					let msg = ''//this.$Func.checkSameShelvesInvOut(newPorderItem,'string')
					if(msg!=''){
						this.$Api.msg(msg)
						return
					}else{
						//新增记录
						this.addOrder(bill,billentry)
					}
				}
			},
			//完成
			async addOrder(bill,billentry){
				//编辑，先删除本地旧单据
				if(this.operflag=='edit'){
					await this.$Db.deleteTableData('stockbill','FBillNo',bill.FBillNo)
					await this.$Db.deleteTableData('stockbillentry','FBillNo',bill.FBillNo)
				}
				
				uni.showLoading({mask:true})
				this.$Db.addOrder(5,bill,billentry).then(res=>{
					this.$Api.msg('添加成功','success')
					this.reset()
					uni.hideLoading();
				}).catch(err=>{
					this.$Api.msg('添加失败','error')
					this.$Db.addlog('添加销售出库',err)
					uni.hideLoading();
				})
			},
			//重置表单
			reset() {
				//日期重置
				this.totalNum = 0
				this.poorder = {}
				this.porderItem = []
				this.planItem = []
				this.$set(this.poorder, 'pcode', ''); // 清空对象属性
				this.$set(this.poorder, 'cdepname', ''); // 清空对象属性
				this.$set(this.poorder, 'cUser_Name', ''); // 清空对象属性
				this.$refs.thead.reset() //初始化
			},
		}
	}
</script>
<style lang="scss">
</style>